# 执行前，统一的前置处理
from Z_other.unit_for_excel.operation_excel import OperationExcel
from Z_other.unit_for_excel import col_num
from util.operation_json import OperetionJson
from config.file_config import FilePath
# from util.connect_db import OperationMysql
from logs.user_log import UserLog
import json
op_json = OperetionJson()
path = FilePath()
log = UserLog().get_log()


class GetData:

	def __init__(self,excel_sheel=None):
		if excel_sheel is None:
			self.opera_excel = OperationExcel()
		else:
			self.opera_excel = OperationExcel(excel_sheel)

	# 把excel数据载入到ddt
	def load_data(self):
		rows_count = self.get_case_lines()
		for i in range(1,rows_count):
			# 判断是否执行
			data_list = self.get_line_data(i)
			is_run = data_list[col_num.get_run()]
			if is_run == 'yes':
				yield data_list

	def get_data_by_list(self, data_list):
		# 数据先进行None处理
		list_to_none = []
		for every_one in data_list:
			result = self.to_none(every_one)
			list_to_none.append(result)
		case_id, case_name, url, is_run, cookie, token, header_key, header_type, method, data_key, pre_case_id, pre_key, pos_data_key, expect, result_key, result_01 = list_to_none
		# 记录原始用例数据
		log.debug('获取整行用例数据:\n| %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |' % (
			case_id, case_name, url, is_run, cookie, token, header_key, header_type, method, data_key, pre_case_id,
			pre_key,
			pos_data_key, expect, result_key))
		# 获取实际的url、headers、data

		url = self.get_request_url_host(url, case_id)
		headers = self.get_header_for_dict(header_key)
		data_dict = self.get_data_for_dict(data_key)
		data_list_tuple = case_id, case_name, url, cookie, token, headers, header_type, method, data_dict, pre_case_id, pre_key, pos_data_key, expect, result_key
		return data_list_tuple

	# 把空值转成None
	def to_none(self, param):
		if param != '':
			param = param
		else:
			param = None
		return param

	# # 从一行数据中，获取某个数据
	# def get_excel_value(self,col, case_id):
	# 	data_list = self.opera_excel.get_rows_data(case_id)
	# 	excel_value = data_list[col]
	# 	return excel_value

	# 去获取excel行数,就是我们的case个数
	def get_case_lines(self):
		return self.opera_excel.get_lines()

	# 通过row去获取该case的整行数据
	def get_line_data(self,row):
		rows_data = self.opera_excel.get_row_values(row)
		return rows_data

	# 返回host+url
	def get_request_url_host(self, url, case_id):
		if 'tqyb'in case_id:
			host_url = url
		else:
			host = path.host(case_id)
			host_url = host+url
		return host_url

	# 通过data关键字,拿到data的json数据
	def get_data_change_type(self, data_dict, headers_type):
		# data_dict = self.get_data_for_dict(data_key)
		log.debug('请求进行data格式处理，header_type为："%s"' % headers_type)
		if headers_type == 'json' and type(data_dict) is not str:
			request_data = json.dumps(data_dict)
		elif headers_type == 'x_www_form' and type(data_dict) is not dict:
			request_data = json.loads(data_dict)
		else:
			request_data = data_dict
		return request_data

	# 根据data关键字获取data的dict数据
	def get_data_for_dict(self,data_key):
		log.debug('通过data关键字获得data的dict数据')
		try:
			request_data = op_json.get_data(path.user(), data_key)
		except:
			request_data =None
		return request_data

	# 根据header关键字获取header的dict数据
	def get_header_for_dict(self,header_key):
		# headers_data = self.get_header_data(row)
		log.debug('通过header关键字获得header的dict数据')
		if header_key != None:
			try:
				request_header = op_json.get_data(path.header(),header_key)
				return request_header
			except:
				log.error('获取header_json失败')
		else:
			return None

	def write_result(self,row,value):
		col = int(col_num.get_result())
		self.opera_excel.write_value(row,col,value)

	# 获取数据依赖字段
	def get_depend_field(self,row):
		col = int(col_num.get_field_depend())
		key = self.opera_excel.get_cell_value(row,col)
		log.debug('依赖的key为"%s"' %key)
		if key == "":
			return None
		elif 'list' in key:
			key_split = key.split(".")
			return int(key_split[1])
		else:
			# 将excel上的依赖key分割，并转格式为int（if 可以转的话）
			# 如 products.0.quantity
			key_split = key.split(".")
			# print (excel_s)
			excel_int_list = []
			for i in key_split:
				try:
					int_i = int(i)
				except:
					res = i
				else:
					res = int_i
				excel_int_list.append(res)
			log.debug('依赖的key_list为"%s"' %excel_int_list)
			return excel_int_list


	# #通过sql获取预期结果
	# def get_expcet_data_for_mysql(self,row):
	# 	op_mysql = OperationMysql()
	# 	sql = self.get_expcet_data(row)
	# 	res = op_mysql.search_one(sql)
	# 	return res.decode('unicode-escape')


